package com.edu;

import com.edu.interceptor.Interceptor;
import com.edu.interceptor.InterceptorChain;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

public class HandlerMapping {

    private Map<String,HandlerDefinition> mapping;

    private HandlerDefinition definition;

    public InterceptorChain findHandler(HttpServletRequest request){
        String url = request.getServletPath();
        mapping = (Map<String,HandlerDefinition>)request.getServletContext().getAttribute(DispatcherServlet.DEFINITIONS);
        definition = mapping.get(url);
        InterceptorChain chain = new InterceptorChain();
        chain.setDefinition(definition);
        creatInterceptors(chain,request);
        chain.getIterator();
        return chain;
    }

    private void creatInterceptors(InterceptorChain chain, HttpServletRequest request){
        List<Class<?>> interceptors = (List<Class<?>>)request.getServletContext().getAttribute(DispatcherServlet.INTERCEPTORS);
        for (Class<?> interceptor:interceptors){
            chain.add(creatInterceptorInstance(interceptor));
        }
    }

    private Interceptor creatInterceptorInstance(Class<?> interceptor){
        try {
           return  (Interceptor)interceptor.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
